#include "input.h"
#include "SDL2/SDL.h"

inline Input::Key Input::key_lookup(int keycode)
{
	switch (keycode) {
		case SDLK_ESCAPE:
			return KEY_ESCAPE;
		case SDLK_RETURN:
			return KEY_RETURN;
		case SDLK_w:
			return KEY_w;
		case SDLK_a:
			return KEY_a;
		case SDLK_s:
			return KEY_s;
		case SDLK_d:
			return KEY_d;
		default:
			return KEY_UNIMPLEMENTED;
	}
}

void Input::query(State& state, std::shared_ptr<Scene> active_scene)
{
	SDL_Event event;

	while (SDL_PollEvent(&event)) {
		switch (event.type) {
			case SDL_QUIT:
				state.quit = true;
				break;
			
			case SDL_WINDOWEVENT: {
				switch (event.window.event) {
					case SDL_WINDOWEVENT_SIZE_CHANGED: {
						state.window_w = event.window.data1;
						state.window_h = event.window.data2;
						state.resized = true;
					}
				}
			}

			case SDL_KEYDOWN: {
				pressed_keys[key_lookup(event.key.keysym.sym)] = true;
				break;
			}

			case SDL_KEYUP: {
				pressed_keys[key_lookup(event.key.keysym.sym)] = false;
				break;
			}

			case SDL_MOUSEBUTTONUP: {
				switch (event.button.button) {
					case SDL_BUTTON_LEFT: {
						for (auto& b : active_scene->get_buttons()) {
							/* collision detection lol */
							if (b.vec22[DST].x < event.button.x &&
								b.vec22[DST].x + b.vec22[DST].w > event.button.x &&
								b.vec22[DST].y < event.button.y &&
								b.vec22[DST].y + b.vec22[DST].h > event.button.y)
								b.callback();
						}
						break;
					}
				}
				break;
			}

			default:
				break;
		}
	}
}